<template>
  <div v-loading="loading" class="rc-cont">
    <template v-if="titleShow">
      <flexbox v-if="!isSeas" class="rc-head" direction="row-reverse">
        <el-button class="xr-btn--orange rc-head-item" icon="el-icon-plus"
                   type="primary" @click="createClick('title')">新建发票抬头
        </el-button>
      </flexbox>
      <el-table :data="titleList" :height="tableHeight" stripe
                style="width: 100%;border: 1px solid #E6E6E6;">
        <el-table-column v-for="(item, index) in titleFieldList" :key="index"
                         :prop="item.prop" :label="item.label" :width="item.width"
                         :formatter="titleFieldFormatter" show-overflow-tooltip/>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <!--          <template slot-scope="scope">-->
            <flexbox justify="center">
              <el-button link @click="handleTitle('edit', scope)">编辑</el-button>
              <el-button link @click="handleTitle('delete', scope)">删除</el-button>
            </flexbox>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <flexbox class="rc-head" direction="row-reverse" style="margin-top: 15px;">
      <el-button v-if="!isSeas && invoiceSave"
                 class="xr-btn--orange rc-head-item" icon="el-icon-plus"
                 type="primary" @click="createClick('invoice')">新建发票
      </el-button>
    </flexbox>
    <el-table :data="list" :height="mainTableHeight"
              :cell-class-name="cellClassName"
              stripe style="width: 100%;border: 1px solid #E6E6E6;" @row-click="handleRowClick">
      <el-table-column v-for="(item, index) in fieldList" :key="index"
                       :prop="item.prop" :formatter="invoicefieldFormatter"
                       :label="item.label" :width="item.width" show-overflow-tooltip/>
      <el-table-column v-if="invoiceUpdateInvoiceStatus" :resizable="false"
                       label="操作" fixed="right" width="150">
        <template #default="scope">
          <!--        <template slot-scope="scope">-->
          <el-button
              :disabled="scope.row.invoiceStatus == 1"
              :type="scope.row.invoiceStatus == 1 ? '' : 'primary'"
              plain
              @click="markReceivables(scope)">{{ scope.row.invoiceStatus == 1 ? '已开票' : '标记为开票' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <c-r-m-full-screen-detail :visible.sync="showFullDetail" :id="showFullId"
                              crm-type="invoice" @handle="detailHandle"/>
    <create v-if="isCreate"
            :action="createAction" @save-success="getInvoiceList" @close="isCreate=false"/>
    <invoice-title-set v-model:visible="titleCreateShow"
                       :customer-id="id" :detail="titleDetail" @change="getTitleList"/>
    <mark-invoice v-model:visible="markShow" :detail="rowDetail" @change="getInvoiceList"/>
  </div>
</template>

<script setup>
import {
  crmCustomerInvoiceAPI,
  crmCustomerInvoiceInfoAPI
} from '/src/api/crm/customer.js'
import {crmContractInvoiceAPI} from '/src/api/crm/contract.js'
import {crmInvoiceDeleteInvoiceInfoAPI} from '/src/api/crm/invoice.js'

import CheckStatusMixin from '/src/mixins/CheckStatusMixin.js'
import InvoiceTitleSet from '../../invoice/components/InvoiceTitleSet.vue'
import MarkInvoice from '../../invoice/components/MarkInvoice.vue'
import Create from '../../invoice/Create.vue'
import {getPermissionByKey} from '/src/utils/index.js'
import {mapState} from "pinia";
import {useErpUserStore} from "../../../../store/modules/usererp.js";
import {watch,computed,ref,nextTick,getCurrentInstance} from "vue";
import CRMFullScreenDetail from "/src/components/CRMFullScreenDetail.vue"

import {useCheckStatusHook} from '/src/hooks/useCheckStatusHook.js'
import {useNumberHook} from "@/hooks/useNumberHook.js";
const {separator} = useNumberHook();
// 引入消息总线
const cxt  = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus


const hookCheckStatusMixin = useCheckStatusHook()

defineOptions({
  name: 'RelativeInvoice', // 相关回访
})

const props = defineProps({
  /** 模块ID */
  id: [String, Number],
  /** 没有值就是全部类型 有值就是当个类型 */
  crmType: {
    type: String,
    default: ''
  },
  /** 是公海 默认是客户 */
  isSeas: {
    type: Boolean,
    default: false
  },
  /** 客户和 合同下 可新建 抬头 */
  detail: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const loading = ref(false)
const list = ref([])
const fieldList = ref([])
const tableHeight = ref('250px')
const showFullDetail = ref(false)
const showFullId = ref('') // 查看全屏详情的 ID
const createAction = ref(null)
const isCreate = ref(false) // 新建发票发票
const titleList = ref([])
const titleFieldList = ref([])

const titleCreateShow = ref(false)
const titleDetail = ref(null)

const rowDetail = ref({})
const markShow = ref(false)


const rootTabs = inject('rootTabs')


const crm = computed(() => {
  const  erpUserStore = useErpUserStore()
  return erpUserStore.crm
})

// 发票title展示
const titleShow = computed(() => {
  return props.crmType === 'customer'
})

// 发票列表高
const mainTableHeight = computed(() => {
  return titleShow.value ? '250px' : '400px'
})

const invoiceSave = computed(()=> {
  return !!getPermissionByKey('crm.invoice.save')
})
// 是否能操作
const invoiceUpdateInvoiceStatus = computed(() =>{
  return !!getPermissionByKey('crm.invoice.updateInvoiceStatus')
})

watch(() => props.id, (val) => {
  list.value = []
  titleList.value = []
  getInvoiceList()
  getTitleList()
})

watch(() => rootTabs.currentName, (val) => {
  if (val === 'RelativeInvoice') {
    getInvoiceList(false)
    getTitleList(false)
  }
})

/**
 * 抬头列表
 */
function getTitleList(load = true) {
  if (titleShow.value) {
    loading.value = load
    crmCustomerInvoiceInfoAPI({customerId: props.id, pageType: 0})
        .then(res => {
          loading.value = false
          titleList.value = res.data.data.list
        }).catch(() => {
          loading.value = false
        })
  }
}

/**
 * 发票列表
 */
function getInvoiceList(load = true) {
  loading.value = load
  const request = {
    customer: crmCustomerInvoiceAPI,
    contract: crmContractInvoiceAPI
  }[props.crmType]

  const params = {pageType: 0}
  params[`${props.crmType}Id`] = props.id
  request(params).then(res => {
        loading.value = false
        const resData = res.data || {}
        list.value = resData.list || []
  }).catch(() => {
    loading.value = false
  })
}

/**
 /**
 * 当某一行被点击时会触发该事件
 */
function handleRowClick(row, column, event) {
  if (column.property == 'invoiceApplyNumber') {
    showFullId.value = row.invoiceId
    showFullDetail.value = true
  }
}

/**
 * 新建发票和抬头
 */
function createClick(type) {
  if (type == 'invoice') {
    if (props.crmType === 'customer') {
      createAction.value = {
        type: 'relative',
        crmType: props.crmType,
        data: {
          customer: props.detail,
          contactsName: props.detail.contactsName,
          contactsMobile: props.detail.contactsMobile,
          contactsAddress: props.detail.contactsAddress
        }
      }
    } else if (props.crmType === 'contract') {
      createAction.value = {
        type: 'relative',
        crmType: props.crmType,
        data: {
          customer: {
            customerName: props.detail.customerName,
            customerId: props.detail.customerId
          },
          contract: props.detail,
          contactsName: props.detail.contactsName,
          contactsMobile: props.detail.contactsMobile,
          contactsAddress: props.detail.contactsAddress
        }
      }
    }
    isCreate.value = true
  } else if (type == 'title') {
    titleDetail.value = null
    titleCreateShow.value = true
  }
}

/**
 * 编辑操作
 */
function handleTitle(type, item) {
  if (type == 'edit') {
    titleDetail.value = item.row
    titleCreateShow.value = true
  } else if (type == 'delete') {
    ElMessageBox.confirm('您确定要删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      crmInvoiceDeleteInvoiceInfoAPI({
        infoId: item.row.infoId
      }).then(res => {
        titleList.value.splice(item.$index, 1)
        ElMessage.success({message:'删除成功'})
      }).catch(() => {

      })})
        .catch(() => {})
  }
}

/**
 * 发票格式化字段
 */
function invoicefieldFormatter(row, column) {
  if (column.property === 'checkStatus') {
    return getStatusName(row.checkStatus)
  } else if (column.property == 'invoiceType') {
    return {
      1: '增值税专用发票',
      2: '增值税普通发票',
      3: '国税通用机打发票',
      4: '地税通用机打发票',
      5: '收据'
    }[row[column.property]]
  } else if (column.property == 'contractMoney' || column.property == 'invoiceMoney') {
    return separator(row[column.property] || 0)
  }
  return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
}

/**
 * 抬头格式化字段
 */
function titleFieldFormatter(row, column) {
  if (column.property === 'titleType') {
    return {
      1: '单位',
      2: '个人'
    }[row[column.property]]
  }
  return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
}

/**
 * 通过回调控制class
 */
function cellClassName({row, column, rowIndex, columnIndex}) {
  if (column.property === 'invoiceApplyNumber') {
    return 'can-visit--underline'
  } else {
    return ''
  }
}

/**
 * 详情操作
 */
function detailHandle(data) {
  if (data.type === 'delete') {
    getInvoiceList()
    nextTick(() => {
      bus.emit('crm-tab-num-update')
    })
  }
}

/**
 * 开票操作
 */
function markReceivables(scope) {
  rowDetail.value = scope.row
  markShow.value = true
}



</script>


<script type="text/javascript">
export default {
  // components: {
  //   Create,
  //   InvoiceTitleSet,
  //   MarkInvoice,
  //
  // },
  // mixins: [CheckStatusMixin],
  props: {},

  data() {
    return {}
  },

  // inject: ['rootTabs'],

  computed: {
    // ...mapGetters(['crm']),
    // ...mapState(useErpUserStore, ['crm']),
  },
  watch: {

  },

  mounted() {
    titleFieldList.value = [
      {prop: 'titleType', width: '120', label: '抬头类型'},
      {prop: 'invoiceTitle', width: '120', label: '开票抬头'},
      {prop: 'taxNumber', width: '120', label: '纳税人识别号'},
      {prop: 'depositBank', width: '120', label: '开户行'},
      {prop: 'depositAccount', width: '120', label: '开户账号'},
      {prop: 'depositAddress', width: '120', label: '开票地址'},
      {prop: 'telephone', width: '120', label: '电话'},
      {prop: 'ownerUserName', width: '120', label: '创建人'},
      {prop: 'createTime', width: '120', label: '创建时间'}
    ]

    getTitleList()

    fieldList.value = [
      {prop: 'invoiceApplyNumber', width: '120', label: '发票申请编号'},
      {prop: 'contractNum', width: '120', label: '合同编号'},
      {prop: 'contractMoney', width: '120', label: '合同金额'},
      {prop: 'invoiceMoney', width: '120', label: '开票金额（元）'},
      {prop: 'invoiceDate', width: '120', label: '开票日期'},
      {prop: 'realInvoiceDate', width: '120', label: '实际开票日期'},
      {prop: 'invoiceType', width: '120', label: '开票类型'},
      {prop: 'invoiceNumber', width: '120', label: '发票号码'},
      {prop: 'logisticsNumber', width: '120', label: '物流单号'},
      {prop: 'ownerUserName', width: '120', label: '负责人'},
      {prop: 'checkStatus', width: '120', label: '审核状态'}
    ]
    getInvoiceList()
  },

  methods: {

  }
}
</script>
<style lang="scss" scoped>
@import '../../styles/relativecrm';
</style>
